Strings¶
In [1]:
'this is a string'
Out[1]:
'this is a string'
🎨 len
¶
In [2]:
len('word and word')
Out[2]:
13
You can use len
to get the length of a string.
🖌 Building Strings¶
In [3]:
'fire' + 'place'
Out[3]:
'fireplace'
In [4]:
'yo' * 2
Out[4]:
'yoyo'
In [5]:
'nan ' * 16 + 'batman!'
Out[5]:
'nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan batman!'
🖌 +=
¶
In [6]:
message = 'Hello'
message = message + ' world!'
message
Out[6]:
'Hello world!'
In [7]:
message = 'Hello'
message += ' world!'
message
Out[7]:
'Hello world!'
🖌 String Iteration¶
In [10]:
for letter in 'this is a string':
print(letter)
t h i s i s a s t r i n g
🎨 Character classes¶
In [11]:
'a'.isalpha(), '8'.isalpha()
Out[11]:
(True, False)
In [12]:
'abcdefg'.isalpha(), 'abc1234'.isalpha(), 'abc!'.isalpha()
Out[12]:
(True, False, False)
In [16]:
'a'.isdigit(), '8'.isdigit()
Out[16]:
(False, True)
In [14]:
'12345'.isdigit(), '12345pi'.isdigit(), '123.456'.isdigit()
Out[14]:
(True, False, False)
In [17]:
'a'.isalnum(), '8'.isalnum()
Out[17]:
(True, True)
In [18]:
'12345'.isalnum(), '12345pi'.isalnum(), '123.456'.isalnum()
Out[18]:
(True, True, False)
In [19]:
'a'.isspace(), '8'.isspace(), ' '.isspace()
Out[19]:
(False, False, True)
In [20]:
'A'.islower(), 'A'.isupper()
Out[20]:
(False, True)
In [21]:
'a'.islower(), 'a'.isupper(), '9'.islower(), '9'.isupper()
Out[21]:
(True, False, False, False)
In [22]:
'a'.upper(), 'a'.lower()
Out[22]:
('A', 'a')
In [25]:
'A'.upper(), 'A'.lower(), 'hello'.upper(), 'hello'.title()
Out[25]:
('A', 'a', 'HELLO', 'Hello')
In [26]:
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_+=[]{}"\'|:;,./?<> \t\n'
In [27]:
# isalpha
alphas = ''
for character in characters:
if character.isalpha():
alphas += character
print(alphas)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
In [28]:
# isdigit
digits = ''
for character in characters:
if character.isdigit():
digits += character
print(digits)
0123456789
In [29]:
# isalnum
alphanumeric = ''
for character in characters:
if character.isalnum():
alphanumeric += character
print(alphanumeric)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
In [30]:
# isspace
spaces = ''
for character in characters:
if character.isspace():
spaces += character
print(spaces)
😶
In [31]:
# isspace
spaces = []
for character in characters:
if character.isspace():
spaces.append(character)
print(spaces)
for space in spaces:
print(f'>>{space}<<')
[' ', '\t', '\n'] >> << >> << >> <<
In [32]:
# other stuff
symbols = ''
for character in characters:
if not character.isspace() and not character.isalnum():
symbols += character
print(symbols)
`~!@#$%^&*()-_+=[]{}"'|:;,./?<>
In [33]:
# upper and lower
uppers = ''
lowers = ''
for character in characters:
if character.isupper():
uppers += character
elif character.islower():
lowers += character
print(uppers)
print(lowers)
ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
👩🏻🎨 No Spaces¶
Write a function that replaces all space characters with dashes.
In [36]:
def no_spaces(text: str) -> str:
"""Replace all whitespace characters with dashes"""
dash_string = ''
for char in text:
if char.isspace():
char = '-'
dash_string += char
# print(dash_string)
return dash_string
In [37]:
print(no_spaces('BYU is the place to be.'))
BYU-is-the-place-to-be.
In [38]:
message = """This is a long,
multiline "string".
It has multiple lines.
That is what "multiline" means. :)"""
print(message)
print()
print(no_spaces(message))
This is a long, multiline "string". It has multiple lines. That is what "multiline" means. :) This-is-a-long,-multiline-"string".-It-has-multiple-lines.-That-is-what-"multiline"-means.-:)
In [39]:
print(no_spaces('Goodbye spaces \t tabs \n and newlines'))
Goodbye-spaces---tabs---and-newlines
👨🏾🎨 Numbers?¶
Write a function that replaces every digit in a string with ?
In [40]:
def no_numbers(text: str) -> str:
"""Replace every digit with ?"""
question_string = ''
for char in text:
if char.isdigit():
char = '?'
question_string += char
# if char.isdigit():
# question_string += '?'
# else:
# question_string += char
return question_string
In [41]:
no_numbers('There were 7 people.')
Out[41]:
'There were ? people.'
In [42]:
no_numbers('15 out of 25 have more than 17.3% contamination.')
Out[42]:
'?? out of ?? have more than ??.?% contamination.'
In [43]:
no_numbers('2 + 2 = 5, for large values of 2.')
Out[43]:
'? + ? = ?, for large values of ?.'
🧑🏻🎨 Sum of Digits¶
Add up all the digits found in a string.
In [47]:
def add_digits(text: str) -> int:
"""Add all the digits found in the `text`.
>>> add_digits('123foo')
6
"""
total = 0
for char in text:
if char.isdigit():
total += int(char)
return total
# return sum(int(char) for char in text if char.isdigit())
In [49]:
add_digits('123foo')
Out[49]:
6
In [50]:
add_digits('10 students ate 6 oranges and 42 students ate 7 pears.')
Out[50]:
20
🧑🏽🎨 Organized¶
Write a program that "organizes" user input.
"Organized" text means that all the characters are reordered to this sequence:
- lowercase letters
- uppercase letters
- digits
- everything else
- whitespace is removed
organize.py
¶
Text: Hello, what is your name?
ellowhatisyournameH,?
Text: BYU is my favorite school!
ismyfavoriteschoolBYU!
Text: 3.14159 is a loose approx. for PI.
isalooseapproxforPI314159...
Text:
Key Ideas¶
- String iteration
'foo' + 'bar'
,'BYU! ' * 5
.isalpha()
,.isdigit()
,.isalnum()
,.isspace()
,.isupper()
,.islower()
.upper()
,.lower()
+=